extends CharacterBody2D

# 在角色脚本顶部添加纹理资源
@export var idle_texture: Texture2D
@export var run_texture: Texture2D

# 角色属性
@export var speed: float = 100.0
@export var acceleration: float = 500.0
@export var friction: float = 500.0

# 攻击属性
@export var attack_damage: int = 25
@export var attack_range: float = 32.0  # 更新攻击范围以匹配圆形碰撞
@export var attack_cooldown: float = 0.8  # 增加冷却时间，因为360度攻击更强
@export var attack_duration: float = 0.6  # 增加攻击持续时间以完成360度旋转
@export var weapon_rotation_speed: float = 10.0  # 武器旋转速度（弧度/秒）

# 生命值属性
@export var max_health: int = 100
@export var current_health: int = 100

# 节点引用
@onready var sprite: Sprite2D = $Sprite2D
@onready var animation_player: AnimationPlayer = $AnimationPlayer
@onready var weapon_sprite: Sprite2D = $WeaponSprite
@onready var attack_area: Area2D = $AttackArea
@onready var attack_collision: CollisionShape2D = $AttackArea/AttackCollision
@onready var slash_effect: Sprite2D = $AttackEffect/SlashEffect
@onready var health_bar: PlayerHealthBar = $HealthBar
@onready var damage_label: Label = $DamageLabel
# @onready var effect_animator: AnimationPlayer = $AttackEffect/EffectAnimator  # 不再需要

# 状态变量
var last_direction: Vector2 = Vector2.DOWN
var is_moving: bool = false
var is_attacking: bool = false
var attack_timer: float = 0.0
var is_dead: bool = false

# 360度攻击相关变量
var is_spinning_attack: bool = false
var weapon_start_rotation: float = 0.0
var weapon_current_rotation: float = 0.0
var attacked_enemies_this_spin: Array[Node] = []  # 本次旋转攻击中已攻击的敌人
var spin_attack_tween: Tween

# 攻击目标列表
var enemies_in_range: Array[Node] = []

# 在脚本顶部添加边界变量
# 游戏边界（基于TileMap尺寸而不是viewport）
var game_bounds: Rect2
var half_sprite_size: Vector2
var tilemap: TileMap  # TileMap引用

# 信号
signal died
signal health_changed(current: int, maximum: int)

func _ready():
	setup_health_system()
	setup_attack_system()
	setup_textures()
	setup_screen_bounds()
	# 确保动画播放器准备就绪后再播放动画
	if animation_player:
		animation_player.play("idle")

func setup_health_system():
	# 初始化血量
	current_health = max_health
	
	# 设置碰撞层（确保敌人能检测到玩家，并与墙壁碰撞）
	collision_layer = 1  # 玩家层
	collision_mask = 2   # 与墙壁等障碍物碰撞
	
	print("🎯 玩家碰撞设置: layer=", collision_layer, " mask=", collision_mask)
	
	# 设置血条
	if health_bar:
		health_bar.set_health(current_health, max_health)
		health_bar.show_health_bar()  # 玩家血条始终显示
	
	# 设置伤害标签
	if damage_label:
		damage_label.visible = false

func setup_attack_system():
	# 连接攻击区域信号
	if attack_area:
		attack_area.body_entered.connect(_on_enemy_entered_attack_range)
		attack_area.body_exited.connect(_on_enemy_exited_attack_range)
		
		# 🔧 修复碰撞层：让攻击区域监听第4层（敌人层）
		attack_area.collision_mask = 4
	
	# 初始化武器位置
	weapon_sprite.visible = false
	
	# 初始化特效
	slash_effect.visible = false
	slash_effect.texture = load("res://Art/v1.1 dungeon crawler 16X16 pixel pack/effects (new)/slash_effect_anim_spritesheet.png")
	slash_effect.hframes = 3

func setup_textures():
	# 预加载纹理（之前的代码保持不变）
	 # 预加载纹理
	idle_texture = load("res://Art/v1.1 dungeon crawler 16X16 pixel pack/heroes/knight/knight_idle_spritesheet.png")
	run_texture = load("res://Art/v1.1 dungeon crawler 16X16 pixel pack/heroes/knight/knight_run_spritesheet.png")
	 # 设置初始纹理
	sprite.texture = idle_texture
	

func _physics_process(delta):
	if is_dead:
		return
		
	handle_attack_timer(delta)
	handle_input(delta)
	move_and_slide()
	clamp_to_screen_bounds()
	update_animation()
	
	# 处理旋转攻击
	if is_spinning_attack:
		update_spinning_attack(delta)

func _input(event):
	if event.is_action_pressed("attack") and can_attack():
		start_spinning_attack()

func can_attack() -> bool:
	return not is_dead and not is_attacking and attack_timer <= 0.0

func start_spinning_attack():
	print("🌪️ 开始360度旋转攻击！")
	is_attacking = true
	is_spinning_attack = true
	attack_timer = attack_cooldown
	
	# 清空本次攻击的敌人列表
	attacked_enemies_this_spin.clear()
	
	# 记录武器起始旋转角度（从玩家右侧开始）
	weapon_start_rotation = 0.0  # 从右侧开始旋转，更直观
	weapon_current_rotation = weapon_start_rotation
	
	# 显示武器并设置初始位置
	weapon_sprite.visible = true
	weapon_sprite.scale = Vector2(1.5, 1.5)  # 增大武器以增强视觉效果
	weapon_sprite.modulate = Color(1.2, 1.2, 1.5, 1.0)  # 添加淡蓝色光效
	
	# 设置武器初始位置
	var distance = 24.0  # 增加旋转半径，让旋转更明显
	weapon_sprite.position = Vector2(distance, 0)
	weapon_sprite.rotation = weapon_start_rotation
	
	# 播放攻击动画
	animation_player.play("attack")
	
	# 创建旋转Tween with 缓动效果
	if spin_attack_tween:
		spin_attack_tween.kill()
	
	spin_attack_tween = create_tween()
	spin_attack_tween.set_loops(1)
	
	# 武器360度旋转，使用缓动函数让开始和结束更流畅
	var target_rotation = weapon_start_rotation + TAU  # TAU = 2π，即360度
	spin_attack_tween.tween_method(update_weapon_rotation, weapon_start_rotation, target_rotation, attack_duration)
	spin_attack_tween.tween_callback(end_spinning_attack)
	
	# 设置缓动类型，让旋转更有冲击感
	spin_attack_tween.set_ease(Tween.EASE_OUT)
	spin_attack_tween.set_trans(Tween.TRANS_BACK)
	
	# 显示增强的旋转特效
	show_enhanced_spinning_effects()
	
	# 添加屏幕震动效果
	add_screen_shake()

func update_weapon_rotation(rotation: float):
	weapon_current_rotation = rotation
	if weapon_sprite and is_instance_valid(weapon_sprite):
		# 增加旋转半径，让武器轨迹更明显
		var distance = 24.0 + sin(rotation * 2) * 4.0  # 添加轻微的距离变化，更有动感
		var weapon_pos = Vector2(cos(rotation), sin(rotation)) * distance
		
		weapon_sprite.position = weapon_pos
		weapon_sprite.rotation = rotation + PI/2  # 让武器始终指向旋转方向
		
		# 创建武器轨迹特效
		create_weapon_trail(weapon_pos)

func create_weapon_trail(weapon_pos: Vector2):
	# 创建武器轨迹残影
	var trail = Sprite2D.new()
	get_parent().add_child(trail)
	trail.global_position = global_position + weapon_pos
	trail.texture = weapon_sprite.texture
	trail.rotation = weapon_sprite.rotation
	trail.scale = weapon_sprite.scale * 0.8
	trail.modulate = Color(1.0, 0.8, 0.8, 0.6)  # 淡红色半透明
	trail.z_index = weapon_sprite.z_index - 1
	
	# 轨迹淡出动画
	var trail_tween = create_tween()
	trail_tween.parallel().tween_property(trail, "modulate:a", 0.0, 0.3)
	trail_tween.parallel().tween_property(trail, "scale", Vector2.ZERO, 0.3)
	trail_tween.tween_callback(func(): if trail and is_instance_valid(trail): trail.queue_free())

func show_enhanced_spinning_effects():
	# 创建多层特效
	
	# 1. 主要斩击特效（保持原有的）
	slash_effect.visible = true
	slash_effect.scale = Vector2(2.5, 2.5)  # 进一步放大
	slash_effect.position = Vector2.ZERO
	slash_effect.modulate = Color(1.5, 1.2, 0.8, 0.8)  # 金色光效
	
	# 2. 创建外圈能量环特效
	var energy_ring = Sprite2D.new()
	get_parent().add_child(energy_ring)
	energy_ring.global_position = global_position
	energy_ring.texture = load("res://Art/v1.1 dungeon crawler 16X16 pixel pack/effects (new)/slash_effect_anim_spritesheet.png")
	energy_ring.hframes = 3
	energy_ring.scale = Vector2(3.5, 3.5)
	energy_ring.modulate = Color(0.8, 1.2, 1.5, 0.4)  # 蓝色外环
	energy_ring.name = "EnergyRing"
	
	# 3. 创建内圈冲击波
	var shockwave = Sprite2D.new()
	get_parent().add_child(shockwave)
	shockwave.global_position = global_position
	shockwave.texture = load("res://Art/v1.1 dungeon crawler 16X16 pixel pack/effects (new)/explosion_anim_spritesheet.png")
	shockwave.hframes = 7
	shockwave.scale = Vector2(0.5, 0.5)
	shockwave.modulate = Color(1.0, 1.0, 1.0, 0.6)
	shockwave.name = "Shockwave"
	
	# 主特效动画
	var main_tween = create_tween()
	main_tween.set_loops(1)
	
	# 斩击特效旋转
	main_tween.parallel().tween_property(slash_effect, "rotation", TAU, attack_duration)
	main_tween.parallel().tween_method(
		func(frame): 
			if slash_effect and is_instance_valid(slash_effect):
				slash_effect.frame = int(frame) % 3,
		0.0, attack_duration * 8, attack_duration
	)
	
	# 能量环反向旋转
	main_tween.parallel().tween_property(energy_ring, "rotation", -TAU, attack_duration)
	main_tween.parallel().tween_property(energy_ring, "scale", Vector2(4.0, 4.0), attack_duration)
	main_tween.parallel().tween_property(energy_ring, "modulate:a", 0.0, attack_duration)
	
	# 冲击波扩散
	main_tween.parallel().tween_property(shockwave, "scale", Vector2(2.0, 2.0), attack_duration * 0.3)
	main_tween.parallel().tween_property(shockwave, "modulate:a", 0.0, attack_duration * 0.5)
	main_tween.parallel().tween_method(
		func(frame): 
			var parent = get_parent()
			if parent:
				var wave = parent.get_node_or_null(NodePath("Shockwave"))
				if wave:
					wave.frame = int(frame) % 7,
		0.0, 6.0, attack_duration * 0.4
	)
	
	# 清理特效
	main_tween.tween_callback(
		func(): 
			if slash_effect and is_instance_valid(slash_effect):
				slash_effect.visible = false
				slash_effect.rotation = 0
				slash_effect.modulate = Color.WHITE
				slash_effect.scale = Vector2(1.0, 1.0)
			
			var parent = get_parent()
			if parent:
				var ring = parent.get_node_or_null(NodePath("EnergyRing"))
				if ring: ring.queue_free()
				var wave = parent.get_node_or_null(NodePath("Shockwave"))
				if wave: wave.queue_free()
	)

func add_screen_shake():
	# 创建屏幕震动效果
	var camera = get_viewport().get_camera_2d()
	if camera:
		var original_offset = camera.offset
		var shake_tween = create_tween()
		
		# 简化的震动效果，避免过于复杂的循环
		var shake_count = 8
		for i in range(shake_count):
			var shake_strength = 4.0 * (1.0 - float(i) / shake_count)  # 逐渐减弱
			var random_offset = Vector2(
				randf_range(-shake_strength, shake_strength),
				randf_range(-shake_strength, shake_strength)
			)
			shake_tween.tween_property(camera, "offset", original_offset + random_offset, attack_duration / shake_count / 2)
			shake_tween.tween_property(camera, "offset", original_offset, attack_duration / shake_count / 2)
		
		# 确保最后回到原位
		shake_tween.tween_property(camera, "offset", original_offset, 0.1)

func update_spinning_attack(delta):
	# 在旋转过程中持续检测并攻击敌人
	check_and_attack_enemies_in_spin()

func check_and_attack_enemies_in_spin():
	for enemy in enemies_in_range:
		# 检查敌人是否已经在本次旋转中被攻击过
		if enemy and enemy.has_method("take_damage") and not enemy in attacked_enemies_this_spin:
			print("⚔️ 旋转攻击击中敌人: ", enemy.name, " 伤害: ", attack_damage)
			enemy.take_damage(attack_damage)
			attacked_enemies_this_spin.append(enemy)  # 标记为已攻击
			
			# 播放击中特效
			show_hit_effect(enemy.global_position)

func end_spinning_attack():
	print("✨ 360度旋转攻击结束")
	is_attacking = false
	is_spinning_attack = false
	
	# 重置武器
	weapon_sprite.visible = false
	weapon_sprite.scale = Vector2(1.0, 1.0)
	weapon_sprite.modulate = Color.WHITE  # 重置颜色
	weapon_sprite.rotation = -0.846485  # 重置到默认角度
	weapon_sprite.position = Vector2(12, -2)  # 重置到默认位置
	
	# 清空攻击敌人列表
	attacked_enemies_this_spin.clear()
	
	print("🎯 本次旋转攻击命中敌人数量: ", attacked_enemies_this_spin.size())

func handle_attack_timer(delta):
	if attack_timer > 0:
		attack_timer -= delta

func update_animation():
	if is_attacking:
		return
	# 更新精灵方向
	if velocity.x < 0:
		sprite.flip_h = true
	elif velocity.x > 0:
		sprite.flip_h = false
	
	# 播放对应动画并切换纹理
	if is_moving and velocity.length() > 5:
		if sprite.texture != run_texture:
			sprite.texture = run_texture
		if animation_player.current_animation != "run":
			animation_player.play("run")
	else:
		if sprite.texture != idle_texture:
			sprite.texture = idle_texture
		if animation_player.current_animation != "idle":
			animation_player.play("idle")

func setup_screen_bounds():
	# 获取TileMap引用
	if not tilemap:
		var game_node = get_tree().get_first_node_in_group("game")
		if game_node:
			tilemap = game_node.get_node_or_null("TileMap")
	
	# 基于TileMap尺寸设置游戏边界
	if tilemap:
		# 获取TileMap的使用区域
		var used_rect = tilemap.get_used_rect()
		var tile_size = tilemap.tile_set.tile_size if tilemap.tile_set else Vector2i(16, 16)
		
		# 计算实际的世界坐标边界
		var world_start = tilemap.map_to_local(used_rect.position)
		var world_end = tilemap.map_to_local(used_rect.position + used_rect.size)
		
		game_bounds = Rect2(world_start, world_end - world_start)
		print("🗺️ 玩家边界设置为TileMap范围: ", game_bounds)
	else:
		# 回退到viewport尺寸
		var viewport_size = get_viewport().get_visible_rect().size
		game_bounds = Rect2(Vector2.ZERO, viewport_size)
		print("⚠️ 未找到TileMap，使用viewport边界: ", game_bounds)
	
	# 计算精灵的一半大小作为边界偏移
	if sprite and sprite.texture:
		half_sprite_size = sprite.texture.get_size() / 2
	else:
		half_sprite_size = Vector2(8, 8)  # 默认值

# 添加边界检测函数（现在主要作为物理碰撞的补充）
func clamp_to_screen_bounds():
	# 如果游戏边界还没有正确设置，尝试重新设置
	if game_bounds.size.x <= 0 or game_bounds.size.y <= 0:
		setup_screen_bounds()
		return
	
	# 由于现在有了物理碰撞，边界检测主要用于防止玩家离开地图边缘
	# 这提供了一个额外的安全网，防止玩家意外离开游戏区域
	var margin = 8.0  # 边界余量
	var clamped_x = clamp(global_position.x, game_bounds.position.x + margin, 
						 game_bounds.position.x + game_bounds.size.x - margin)
	var clamped_y = clamp(global_position.y, game_bounds.position.y + margin, 
						 game_bounds.position.y + game_bounds.size.y - margin)
	
	# 只有当玩家确实超出边界时才进行调整
	if global_position.x != clamped_x or global_position.y != clamped_y:
		global_position = Vector2(clamped_x, clamped_y)
		print("🚧 玩家位置被边界限制: ", global_position)

# ===========================================
# 🩸 玩家血量系统
# ===========================================

func take_damage(amount: int):
	if is_dead:
		return
	
	print("💔 玩家受到伤害: ", amount, " HP: ", current_health, "->", max(0, current_health - amount))
	
	current_health = max(0, current_health - amount)
	health_changed.emit(current_health, max_health)
	
	# 更新血条显示
	update_health_bar()
	
	# 显示伤害数字
	show_damage_number(amount)
	
	# 播放受伤效果
	show_hurt_effect()
	
	# 血条动画效果
	if health_bar:
		health_bar.animate_damage()
	
	if current_health <= 0:
		die()

func update_health_bar():
	if health_bar:
		health_bar.set_health(current_health, max_health)

func show_damage_number(amount: int):
	if damage_label and not is_dead:
		damage_label.text = str(amount)
		damage_label.visible = true
		damage_label.modulate = Color.RED  # 玩家受伤用红色
		damage_label.scale = Vector2(1.5, 1.5)  # 初始放大
		
		var tween = create_tween()
		if tween and damage_label:
			var start_pos = damage_label.position.y
			# 伤害数字动画
			tween.parallel().tween_property(damage_label, "position:y", start_pos - 40, 0.8)
			tween.parallel().tween_property(damage_label, "scale", Vector2(1.0, 1.0), 0.2)
			tween.parallel().tween_property(damage_label, "modulate:a", 0.0, 0.6)
			tween.tween_callback(func(): if damage_label and is_instance_valid(damage_label): 
				damage_label.visible = false
				damage_label.scale = Vector2(1.0, 1.0)  # 重置缩放
				damage_label.position.y = start_pos  # 重置位置
			)

func show_hurt_effect():
	if sprite and not is_dead:
		var tween = create_tween()
		if tween and sprite:
			# 记录原始位置，确保震动后恢复
			var original_position = sprite.position
			# 受击效果：闪红并震动
			tween.parallel().tween_property(sprite, "modulate", Color.RED, 0.1)
			tween.parallel().tween_property(sprite, "position", original_position + Vector2(2, 0), 0.05)
			tween.parallel().tween_property(sprite, "position", original_position + Vector2(-2, 0), 0.1)
			tween.parallel().tween_property(sprite, "position", original_position, 0.05)
			tween.parallel().tween_property(sprite, "modulate", Color.WHITE, 0.3)

func heal(amount: int):
	if is_dead:
		return
	
	current_health = min(max_health, current_health + amount)
	health_changed.emit(current_health, max_health)
	update_health_bar()
	
	print("💚 玩家回复血量: ", amount, " HP: ", current_health, "/", max_health)

func die():
	if is_dead:
		return
	
	is_dead = true
	print("💀 玩家死亡")
	
	# 停止所有移动
	velocity = Vector2.ZERO
	
	# 禁用攻击
	is_attacking = false
	weapon_sprite.visible = false
	slash_effect.visible = false
	
	# 播放死亡动画
	if animation_player and animation_player.has_animation("death"):
		animation_player.play("death")
	else:
		# 如果没有死亡动画，播放简单的死亡效果
		var tween = create_tween()
		if tween and sprite:
			tween.parallel().tween_property(sprite, "modulate", Color(1, 0, 0, 0.5), 0.5)
			tween.parallel().tween_property(sprite, "rotation", PI/4, 0.5)
			tween.parallel().tween_property(sprite, "scale", Vector2(1.2, 1.2), 0.3)
			tween.tween_property(sprite, "scale", Vector2(0.8, 0.8), 0.2)
	
	# 创建死亡特效
	create_death_effect()
	
	# 发出死亡信号
	died.emit()
	
	print("🎮 游戏结束！按R重新开始")

func create_death_effect():
	# 创建死亡爆炸特效
	if get_parent():
		var explosion = Sprite2D.new()
		get_parent().add_child(explosion)
		explosion.global_position = global_position
		explosion.texture = load("res://Art/v1.1 dungeon crawler 16X16 pixel pack/effects (new)/explosion_anim_spritesheet.png")
		explosion.hframes = 7
		explosion.scale = Vector2(1.5, 1.5)  # 玩家死亡特效稍大一些
		explosion.name = "PlayerDeathExplosion"  # 给节点命名
		
		var tween = create_tween()
		if tween:
			tween.tween_method(
				func(frame): 
					var parent = get_parent()
					if parent:
						var effect = parent.get_node_or_null(NodePath("PlayerDeathExplosion"))
						if effect:
							effect.frame = frame, 
				0, 6, 0.6
			)
			tween.tween_callback(
				func(): 
					var parent = get_parent()
					if parent:
						var effect = parent.get_node_or_null(NodePath("PlayerDeathExplosion"))
						if effect:
							effect.queue_free()
			)

# 重生函数（用于重新开始游戏）
func respawn(position: Vector2 = Vector2.ZERO):
	print("🔄 玩家重生开始...")
	
	# 重置死亡状态
	is_dead = false
	current_health = max_health
	
	# 重置所有状态变量
	is_moving = false
	is_attacking = false
	is_spinning_attack = false
	attack_timer = 0.0
	velocity = Vector2.ZERO
	last_direction = Vector2.DOWN
	
	# 重置360度攻击相关变量
	attacked_enemies_this_spin.clear()
	weapon_start_rotation = 0.0
	weapon_current_rotation = 0.0
	if spin_attack_tween:
		spin_attack_tween.kill()
		spin_attack_tween = null
	
	# 完全重置sprite外观和位置
	if sprite:
		sprite.modulate = Color.WHITE
		sprite.rotation = 0
		sprite.scale = Vector2(1, 1)
		sprite.position = Vector2.ZERO  # 重置sprite的本地位置
		sprite.flip_h = false  # 重置翻转状态
		sprite.texture = idle_texture  # 确保使用正确的纹理
	
	# 重置武器和特效
	if weapon_sprite:
		weapon_sprite.visible = false
		weapon_sprite.flip_h = false
		weapon_sprite.position = Vector2(12, -2)  # 重置到默认位置
	
	if slash_effect:
		slash_effect.visible = false
		slash_effect.flip_h = false
		slash_effect.position = Vector2.ZERO  # 重置特效位置
		slash_effect.scale = Vector2(1, 1)  # 重置特效缩放
	
	# 重置攻击区域位置
	if attack_area:
		attack_area.position = Vector2(16, 0)  # 重置到默认位置
	
	# 清空攻击目标列表
	enemies_in_range.clear()
	
	# 重置位置（只有明确提供位置时才设置）
	if position != Vector2.ZERO:
		global_position = position
		print("📍 玩家位置设置为: ", position)
	else:
		print("⏳ 玩家位置将由地牢生成器设置")
	
	# 重置伤害标签
	if damage_label:
		damage_label.visible = false
		damage_label.scale = Vector2(1.0, 1.0)
		damage_label.position = Vector2(-8, -25)  # 重置到默认位置
	
	# 更新UI
	update_health_bar()
	
	# 播放idle动画
	if animation_player:
		animation_player.play("idle")
	
	# 确保玩家的物理状态正确
	set_physics_process(true)
	set_process_input(true)
	
	print("✨ 玩家重生完成！位置: ", global_position)
	print("🔧 玩家状态: 死亡=", is_dead, " 血量=", current_health, "/", max_health)
	print("🔧 物理处理=", is_physics_processing(), " 输入处理=", is_processing_input())

func _on_enemy_entered_attack_range(body):
	print("👁️ 敌人进入攻击范围: ", body.name, " 层级: ", body.collision_layer)
	if body.has_method("take_damage"):
		enemies_in_range.append(body)
	else:
		print("❌ 敌人没有take_damage方法")

func _on_enemy_exited_attack_range(body):
	enemies_in_range.erase(body)

func show_hit_effect(pos: Vector2):
	# 创建击中特效（临时实现）
	var hit_effect = Sprite2D.new()
	get_parent().add_child(hit_effect)
	hit_effect.global_position = pos
	hit_effect.texture = load("res://Art/v1.1 dungeon crawler 16X16 pixel pack/effects (new)/hit_effect_anim_spritesheet.png")
	hit_effect.hframes = 3
	hit_effect.name = "PlayerHitEffect"  # 给节点命名
	
	# 播放击中特效动画
	var tween = create_tween()
	tween.tween_method(
		func(frame): 
			var parent = get_parent()
			if parent:
				var effect = parent.get_node_or_null(NodePath("PlayerHitEffect"))
				if effect:
					effect.frame = frame, 
		0, 2, 0.2
	)
	tween.tween_callback(
		func(): 
			var parent = get_parent()
			if parent:
				var effect = parent.get_node_or_null(NodePath("PlayerHitEffect"))
				if effect:
					effect.queue_free()
	)

func handle_input(delta):
	if is_attacking:
		velocity = velocity.move_toward(Vector2.ZERO, friction * delta * 2)
		return	
	# 获取输入方向
	var input_direction = Vector2(
		Input.get_axis("ui_left", "ui_right"),
		Input.get_axis("ui_up", "ui_down")
	)
	
	# 标准化对角线移动速度
	if input_direction.length() > 1:
		input_direction = input_direction.normalized()
	
	# 应用移动
	if input_direction != Vector2.ZERO:
		velocity = velocity.move_toward(input_direction * speed, acceleration * delta)
		last_direction = input_direction
		is_moving = true
	else:
		velocity = velocity.move_toward(Vector2.ZERO, friction * delta)
		is_moving = false
